/*
 * @Descripttion:
 * @Author: voanit
 * @Date: 2022-05-15 17:11:34
 * @LastEditors: voanit
 * @LastEditTime: 2022-05-19 11:49:08
 */
import React, { useState, useEffect, useRef } from 'react'
import { PlusOutlined } from '@ant-design/icons'
import styles from './index.module.scss'
import ReactQuill from 'react-quill'
import 'react-quill/dist/quill.snow.css'
// import {useDispatch} from 'react-redux'
import {
  Card,
  Breadcrumb,
  Form,
  Input,
  Select,
  Button,
  Space,
  Radio,
  Upload,
  message,
  Modal,
} from 'antd'
import { Link } from 'react-router-dom'
import { useSelector, useDispatch } from 'react-redux'
import {
  actionPublish,
  actionGetArticleInfo,
  actionGetArticleEdit,
} from '@/store/actions/article'
import Channel from '@/components/Channel'
import { useChannels } from '@/hooks/useChannels'
// import { FormItemPrefixContext } from 'antd/lib/form/context'
import history from '@/utils/history'

// import * as obj from 'react-router-dom'
import { useParams } from 'react-router-dom'
export default function Publish() {
  // const channels = useSelector((state) => state.channels)
  const dispatch = useDispatch()
  const { id } = useParams()
  // console.log(id, 6)
  // useEffect(() => {
  //   dispatch(actionChannels)
  // }, [dispatch])
  const channels = useChannels()
  const FILETYPE = ['image/jpg', 'image/gif', 'image/jpeg', 'image/png']
  // 控制type属性
  const [type, setType] = useState(0)
  function beforeUpload(file) {
    // 支持的文件的类型
    const isJpgOrPng = FILETYPE.includes(file.type) //  isNAN()
    if (!isJpgOrPng) {
      message.error('You can only upload JPG/PNG file!')
    }
    const isLt2M = file.size / 1024 / 1024 < 2
    if (!isLt2M) {
      message.error('Image must smaller than 2MB!')
    }
    return isJpgOrPng && isLt2M
  }
  const onChange = ({ file, fileList }) => {
    // console.log(file, fileList, 999)
    if (FILETYPE.includes(file.type)) {
      setFileList(fileList) //fileList  =====所有的图片的集合
      fileRef.current = fileList
      // console.log(fileRef.current, 333)
      fileForm.current.validateFields(['type'])
    }
  }

  /* 图片上传 */

  const [fileList, setFileList] = useState([
    // {
    //   url: 'https://zos.alipayobjects.com/rmsportal/jkjgkEfvpUPVyRjUImniVslZfWPnJuuZ.png',
    // },
  ])
  const fileRef = useRef(fileList) //图片列表数组 []
  const fileForm = useRef(null) //form对象 {}

  const onTypeChange = (e) => {
    // console.log(fileRef.current, 6677)
    setType(e.target.value) // 1|3|0
    console.log(fileRef.current, 77711)
    setFileList(fileRef.current.slice(0, e.target.value)) //fileRef.current：【1，2，3】
  }
  /* 表单提交 */
  const onFinish = async (values) => {
    console.log(values, 2)
    if (values.type === 3 && fileList.length !== 3) {
      return message.warning('封面数量不为3张')
    }
    // 收集图片
    var images = fileList.map((item) => {
      if (item.url) {
        return item.url
      } else {
        // console.log(item.response.data)
        return item.response.data.url
      }
    })
    // console.log(images, 777)

    const { type, ...rest } = values

    // rest['cover'] = {
    //   type,
    //   images,
    // }
    /* 准备发布文章的参数 */
    const data = {
      ...rest,
      cover: {
        type,
        images,
      },
    }
    // console.log(rest, 888)
    // 发送请求
    if (id) {
      // 编辑
      await dispatch(
        actionGetArticleEdit({
          ...data,
          id,
        })
      )
    } else {
      //发布
      dispatch(actionPublish(data))
    }

    /* 成功后跳转回 layout/article */
    history.push('/layout/article')
  }

  /* 存入草稿 */
  const addDraft = async () => {
    /* 
    1-获取数据==表单数据
    2-存入草稿需要传入一个bool  true
    */
    // console.log(fileForm.current.getFieldValue(), 777)
    var images = fileList.map((item) => {
      if (item.url) {
        return item.url
      } else {
        // console.log(item.response.data)
        return item.response.data.url
      }
    })
    // console.log(fileForm.current.getFieldsValue(true), 777)
    const { type, ...rest } = fileForm.current.getFieldsValue(true)
    const data = {
      ...rest,
      cover: {
        images,
        type,
      },
    }
    // console.log(data, 55)
    // 发送请求
    if (id) {
      // 编辑
      await dispatch(
        actionGetArticleEdit(
          {
            ...data,
            id,
          },
          true
        )
      )
    } else {
      dispatch(actionPublish(data, true))
    }
    /* 成功后跳转回 layout/article */
    history.push('/layout/article')
  }

  /* 图片预览 */
  // const onPreview = ({ fileList }) => this.setState({ fileList })
  // const onPreview = ({ fileList }) => setFileList(fileList)
  function getBase64(file) {
    return new Promise((resolve, reject) => {
      const reader = new FileReader()
      reader.readAsDataURL(file)
      reader.onload = () => resolve(reader.result)
      reader.onerror = (error) => reject(error)
    })
  }
  const [isVisible, setIsVisible] = useState(false)
  const [preview, setPreview] = useState('')
  const onPreview = async (file) => {
    if (!file.url && !file.preview) {
      file.preview = await getBase64(file.originFileObj)
    }

    // this.setState({
    //   previewImage: file.url || file.preview,
    //   previewVisible: true,
    //   previewTitle:
    //     file.name || file.url.substring(file.url.lastIndexOf('/') + 1),
    // })
    setIsVisible(true)
    setPreview(file.url || file.preview)
  }

  // 取消
  const handleCancel = () => {
    setIsVisible(false)
  }

  /* 编辑 */
  useEffect(() => {
    async function asyncGetEdit() {
      if (id) {
        // console.log(dispatch(actionGetArticleInfo(id)), 777)
        const articleInfo = await dispatch(actionGetArticleInfo(id))
        // console.log(articleInfo, 7777)
        // 回显数据到表单中
        const article = {
          type: articleInfo.cover.type, // 图片类型
          content: articleInfo.content,
          channel_id: articleInfo.channel_id,
          title: articleInfo.title,
        }
        fileForm.current.setFieldsValue(article)

        // 回显图片
        // setFileList(() => {
        //   fileRef.current = articleInfo.cover.images.map((item) => {
        //     return {
        //       url: item,
        //     }
        //   })
        //   return fileRef.current
        // })
        // setFileList(
        //   articleInfo.cover.images.map((item) => {
        //     fileRef.current.push({
        //       url: item,
        //     })
        //     return {
        //       url: item,
        //     }
        //   })
        // )
        setFileList(() => {
          fileRef.current = articleInfo.cover.images.map((item) => {
            return {
              url: item,
            }
          })
          return fileRef.current
        })
      }
    }
    asyncGetEdit()
  }, [])
  return (
    <div className={styles.root}>
      <Card
        title={
          <Breadcrumb separator=">">
            <Breadcrumb.Item>
              <Link to="/home">首页</Link>
            </Breadcrumb.Item>
            <Breadcrumb.Item>发布文章</Breadcrumb.Item>
          </Breadcrumb>
        }
      >
        <Form
          initialValues={{ channel_id: 2, content: 'content', type }}
          labelCol={{ span: 4 }}
          wrapperCol={{ span: 20 }}
          size="large"
          onFinish={onFinish}
          ref={fileForm}
        >
          <Form.Item
            label="标题"
            name="title"
            rules={[
              {
                required: true,
                message: '标题不能为空',
              },
            ]}
          >
            <Input
              placeholder="请输入文章的标题"
              style={{ width: 400 }}
            ></Input>
          </Form.Item>
          <Form.Item
            label="频道"
            name="channel_id"
            rules={[
              {
                required: true,
                message: '频道不能为空',
              },
            ]}
          >
            {/* <Select style={{ width: 200 }} allowClear placeholder="请选择频道">
              {channels.map((item) => (
                <Select.Option value={item.id} key={item.id}>
                  {item.name}
                </Select.Option>
              ))}
            </Select> */}
            <Channel></Channel>
          </Form.Item>
          <Form.Item
            label="封面"
            name="type"
            rules={[
              {
                validator(_, value) {
                  console.log(_, value, 999878)
                  if (fileList.length !== value) {
                    return Promise.reject(new Error(`请上传${value}张图片`))
                  } else {
                    return Promise.resolve()
                  }
                },
              },
            ]}
          >
            <Radio.Group value={type} onChange={onTypeChange}>
              <Radio value={1}>单图</Radio>
              <Radio value={3}>三图</Radio>
              <Radio value={0}>无图</Radio>
            </Radio.Group>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            {/* 
              action: 上传的地址
              name: 上传的文件的名字 默认file
              fileList: 显示控制上传的图片, 做回填 */}
            <Upload
              listType="picture-card"
              fileList={fileList}
              action={`http://toutiao.itheima.net/v1_0/upload`}
              beforeUpload={beforeUpload}
              name="image"
              onChange={onChange}
              maxCount={type}
              onPreview={onPreview}
            >
              {/* <PlusOutlined /> */}
              {fileList.length < type && <PlusOutlined />}
            </Upload>

            <Modal
              width={800}
              visible={isVisible}
              footer={null}
              onCancel={handleCancel}
            >
              <img alt="example" style={{ width: '100%' }} src={preview} />
            </Modal>
          </Form.Item>

          <Form.Item
            label="内容"
            name="content"
            rules={[
              {
                required: true,
                message: '内容不能为空',
              },
            ]}
          >
            <ReactQuill></ReactQuill>
          </Form.Item>
          <Form.Item wrapperCol={{ offset: 4, span: 20 }}>
            <Space>
              <Button htmlType="submit" type="primary">
                发布文章
              </Button>
              <Button onClick={addDraft}>存入草稿</Button>
            </Space>
          </Form.Item>
        </Form>
      </Card>
    </div>
  )
}
